/**
 * Created by charsen on 16/5/27.
 */
directives.directive('chartManager', ["$rootScope", "tools", "tmp", "$timeout", "$routeParams", function ($rootScope, tools, tmp, $timeout, $routeParams) {
    return {
        restrict: 'E',
        scope: {},
        replace: {},
        link: function (scope, element, attr) {
            var events = {};
            var $ele = $(element);

            // 包围chart的div是一个屏幕的宽
            if (!tools.mobileEnv()) {
                $('.chart-manager-container .charts-container').css({
                    width: document.documentElement.clientWidth - 40 + 'px'
                });
            } else {
                $ele.addClass('p10');
            }

            $('.chart-manager-container .charts-container').on('click', function (e) {
                $rootScope.$broadcast('UNSELECT_EV');
            });

            if ($routeParams.type == 'prod') {
                $timeout(function () {
                    $('.chart-manager-container').height(document.documentElement.clientHeight - $('.editor-header').outerHeight() - 10);
                }, 50);
            } else {
                $timeout(function () {
                    $('.chart-manager-container').height(document.documentElement.clientHeight - $('.editor-header').outerHeight() - $('.editor-shortcut').outerHeight() - $('.field-manager-wrap').outerHeight() - 25);
                }, 50);
            }

            $('.chart-manager-container').on('contextmenu', function (e) {
                if (e.button == 2) {
                    $rootScope.$broadcast('CONTEXTMENU_EV', e.pageX, e.pageY, [
                        {
                            name: '清空所有',
                            icon: 'erase icon',
                            fn: function () {
                                $rootScope.$broadcast('CONFIRM_EV', {
                                    title: '页面清空',
                                    content: '所有图表删除之后不可恢复,确定删除吗?',
                                    btns: {
                                        yes: {
                                            text: "确定删除",
                                            fn: function () {
                                                $rootScope.$broadcast('DEL_CHART_EV');
                                                $rootScope.$broadcast('DEL_SHEET_EV');
                                                $rootScope.$broadcast('DEL_COND_EV');
                                                $rootScope.$broadcast('DEL_ALL_THINGS');
                                            }
                                        },
                                        no: {
                                            text: '取消',
                                            fn: function () {

                                            }
                                        }
                                    }
                                });
                            }
                        },
                        {
                            name: '保存',
                            icon: 'save icon',
                            fn: function () {
                                $rootScope.$broadcast('SAVE_PAGE_EV');
                            }
                        }
                    ]);
                    e.preventDefault();
                } else {
                }
                return false;
            });

            scope.squares = [];
            scope.charts = [];
            scope.sheets = [];
            // 存放图标,文本框等
            scope.objects = {
                text: [],
                images: []
            };
            scope.maps = [];
            scope.conditions = {
                date: [],
                note: [],
                radio: [],
                select: [],
                between: [],
                checkbox: []
            };

            var getAvailableSquare = $rootScope.getAvailableSquare = function () {
                for (var i = 0; i < scope.squares.length; i++) {
                    if (scope.squares[i].used === false) {
                        return {
                            square: scope.squares[i],
                            index: i
                        }
                    }
                }
            }

            $rootScope.getMatchedSquare = function (left, top) {
                for (var i = 0; i < scope.squares.length; i++) {
                    var square = scope.squares[i];
                    if (left > square.left && left < square.left + square.width && top > square.top && top < square.top + square.height) {
                        return square;
                    }
                }
            }

            $rootScope.getMap = scope.getMap = function (id) {
                for (var i = 0; i < scope.maps.length; i++) {
                    if (scope.maps[i].moduleId == id || scope.maps[i].tmpId == id) {
                        return scope.maps[i];
                    }
                }
                return null;
            }

            $rootScope.delMap = scope.delMap = function (id) {
                for (var i = 0; i < scope.maps.length; i++) {
                    if (scope.maps[i].moduleId == id || scope.maps[i].tmpId == id) {
                        scope.maps.splice(i, 1);
                        break;
                    }
                }
            }

            $rootScope.someMapSelected = function () {
                for (var i = 0; i < scope.charts.length; i++) {
                    if (scope.charts[i].selected) {
                        return true;
                    }
                }
                return false;
            }

            $rootScope.getChart = scope.getChart = function (id) {
                for (var i = 0; i < scope.charts.length; i++) {
                    if (scope.charts[i].moduleId == id || scope.charts[i].tmpId == id) {
                        return scope.charts[i];
                    }
                }
                return null;
            }

            $rootScope.delChart = scope.delChart = function (id) {
                for (var i = 0; i < scope.charts.length; i++) {
                    if (scope.charts[i].moduleId == id || scope.charts[i].tmpId == id) {
                        var deletedChart = scope.charts.splice(i, 1)[0];
                        // 标记方格可用
                        if (deletedChart.square_index !== -1) {
                            if (scope.squares && scope.squares.length && scope.squares[deletedChart.square_index]) {
                                scope.squares[deletedChart.square_index].used = false;
                            }
                        }
                        break;
                    }
                }
            }

            $rootScope.someChartSelected = function () {
                for (var i = 0; i < scope.charts.length; i++) {
                    if (scope.charts[i].selected) {
                        return true;
                    }
                }
                return false;
            }

            $rootScope.getSheet = scope.getSheet = function (id) {
                for (var i = 0; i < scope.sheets.length; i++) {
                    if (scope.sheets[i].moduleId == id || scope.sheets[i].tmpId == id) {
                        return scope.sheets[i];
                    }
                }
                return null;
            }

            $rootScope.delSheet = scope.delSheet = function (id) {
                for (var i = 0; i < scope.sheets.length; i++) {
                    if (scope.sheets[i].moduleId == id || scope.sheets[i].tmpId == id) {
                        var deletedSheet = scope.sheets.splice(i, 1)[0];
                        // 标记方格可用
                        if (deletedSheet.square_index !== -1) {
                            if (scope.squares && scope.squares.length && scope.squares[deletedSheet.square_index]) {
                                scope.squares[deletedSheet.square_index].used = false;
                            }
                        }
                        break;
                    }
                }
            }

            $rootScope.someSheetSelected = function () {
                for (var i = 0; i < scope.sheets.length; i++) {
                    if (scope.sheets[i].selected) {
                        return true;
                    }
                }
                return false;
            }

            $rootScope.getCondition = scope.getCondition = function (id) {
                for (var i in scope.conditions) {
                    for (var j = 0; j < scope.conditions[i].length; j++) {
                        if (scope.conditions[i][j].conditionId == id || scope.conditions[i][j].tmpId == id) {
                            return scope.conditions[i][j];
                        }
                    }
                }
                return null;
            }

            $rootScope.delCondition = scope.delCondition = function (id) {
                for (var i in scope.conditions) {
                    for (var j = 0; j < scope.conditions[i].length; j++) {
                        if (scope.conditions[i][j].conditionId == id || scope.conditions[i][j].tmpId == id) {
                            scope.conditions[i].splice(j, 1);
                            break;
                        }
                    }
                }
            }

            $rootScope.someConditionSelected = function () {
                for (var i in scope.conditions) {
                    for (var j = 0; j < scope.conditions[i].length; j++) {
                        if (scope.conditions[i][j].selected) {
                            return true;
                        }
                    }
                }
                return false;
            }

            $rootScope.getText = function (id) {
                if (!scope.objects || scope.objects.text.length === 0) {
                    return;
                }

                for (var i = 0; i < scope.objects.text.length; i++) {
                    if (scope.objects.text[i].tmpId == id) {
                        return scope.objects.text[i];
                    }
                }
            }

            $rootScope.delText = function (id) {
                if (!scope.objects || scope.objects.text.length === 0) {
                    return;
                }

                for (var i = 0; i < scope.objects.text.length; i++) {
                    if (scope.objects.text[i].tmpId == id) {
                        scope.objects.text.splice(i, 1);
                        return;
                    }
                }
            }

            // 划分标准方格事件
            events.STAND_SQUARE_EV_OFF = scope.$on('STAND_SQUARE_EV', function (e, line, row) {
                var space = 20;
                var container_width = $('.chart-manager-container .charts-container').width();
                var width = (container_width - (row + 1) * space) / row;
                var height = width * 0.6;

                scope.squares.length = 0;

                for (var i = 0; i < scope.charts.length; i++) {
                    scope.charts[i].square_index = "";
                }

                for (var i = 0; i < scope.sheets.length; i++) {
                    scope.sheets[i].square_index = "";
                }

                for (var i = 0; i < line; i++) {
                    for (var j = 0; j < row; j++) {
                        scope.squares.push({
                            left: (j + 1) * space + j * width,
                            top: (i + 1) * space + i * height,
                            height: height,
                            width: width,
                            used: false
                        });
                    }
                }
                $timeout(function () {

                }, 0);
            });

            // 监听所有组件被删除的事件
            $rootScope.$on('DEL_ALL_THINGS', function () {
                if (scope.squares.length) {
                    angular.forEach(scope.squares, function (sq) {
                        if (sq.used) {
                            sq.used = false;
                        }
                    });
                }
            });

            // 获取页面数据
            events.PAGE_JSON_EV_OFF = scope.$on('PAGE_JSON_EV', function (e, core) {
                tools.data.acceptPageJson = true;

                if (core) {
                    angular.forEach([].concat(core.charts, core.sheets), function (item) {
                        if (!item) {
                            return;
                        }

                        if (tools.mobileEnv()) {
                            item.mobileMode = true;
                            item.width = 1;
                            item.height = 1;
                        } else {
                            item.mobileMode = false;
                        }
                    });
                    angular.forEach([].concat(core.objects.text, core.objects.images), function (item) {
                        if (!item) {
                            return;
                        }

                        if (tools.mobileEnv()) {
                            item.mobileMode = true;
                            item.height = item.height / item.width;
                            item.width = 1;
                        } else {
                            item.mobileMode = false;
                        }
                    });
                    angular.forEach([].concat(core.conditions.checkbox, core.conditions.radio), function (item) {
                        if (!item) {
                            return;
                        }
                        if (tools.mobileEnv()) {
                            item.mobileMode = true;
                            item.width = 0.6;
                            item.height = 0.8;
                        } else {
                            item.mobileMode = false;
                        }
                    });
                    angular.forEach([].concat(core.conditions.between, core.conditions.date), function (item) {
                        if (!item) {
                            return;
                        }

                        if (tools.mobileEnv()) {
                            item.mobileMode = true;
                            item.width = 1;
                            item.height = 0.5;
                        } else {
                            item.mobileMode = false;
                        }
                    });

                    scope.charts = core.charts;
                    scope.sheets = core.sheets;
                    scope.conditions = core.conditions;
                    scope.objects = core.objects;
                    scope.squares = core.squares || [];

                    if (tools.isEmpty(scope.conditions)) {
                        scope.conditions = {
                            date: [],
                            radio: [],
                            select: [],
                            between: [],
                            checkbox: []
                        }
                    }

                    if (tools.isEmpty(scope.objects)) {
                        scope.objects = {
                            text: [],
                            images: []
                        }
                    }
                }
            });

            // 新增图
            events.ADD_CHART_EV_OFF = $rootScope.$on('ADD_CHART_EV', function (e, type, config) {
                var $container = $(element).find('.charts-container');
                var availableSquare = getAvailableSquare();
                var chartConfig = {
                    left: availableSquare ? availableSquare.square.left / $container.width() : ($ele.scrollLeft() + 100) / $container.width(),
                    top: availableSquare ? availableSquare.square.top / $container.width() : ($ele.scrollTop() + 100) / $container.width(),
                    height: availableSquare ? availableSquare.square.height / $container.width() : 0.2,
                    width: availableSquare ? availableSquare.square.width / $container.width() : 0.3,
                    square_index: availableSquare ? availableSquare.index : -1,
                    measure_for_line: null, // 用于柱状图中的折线字段
                    tmpId: tools.tmpId(),
                    chartType: type,
                    filters: {
                        sortField: '',
                        sortType: ''
                    },
                    setAsSecondY: false,
                    setAsMeanLine: false, //柱状图中设置平均线
                    downDrillValues: [],
                    autoTitle: true,
                    isDrill: false,
                    classifies: [],
                    dimension: [],
                    dimension2:[],
                    measure2: [],
                    measure: [],
                    sortField: '',
                    sortType: '',
                    ctitle: '',
                    moduleId: '',
                    selectRange: {
                        start: null,
                        end: null
                    }
                };

                if (config) {
                    angular.extend(chartConfig, config);
                }

                scope.charts.push(chartConfig);

                // 标注某一个可用的框已经被使用了
                if (availableSquare) {
                    availableSquare.square.used = true;
                }
            });
            // 新增地图
            events.ADD_MAP_EV_OFF = $rootScope.$on('ADD_MAP_EV', function (e, type, config) {
                var $container = $(element).find('.charts-container');
                var availableSquare = getAvailableSquare();
                
                var mapConfig = {
                    left: availableSquare ? availableSquare.square.left / $container.width() : ($ele.scrollLeft() + 100) / $container.width(),
                    top: availableSquare ? availableSquare.square.top / $container.width() : ($ele.scrollTop() + 100) / $container.width(),
                    height: availableSquare ? availableSquare.square.height / $container.width() : 0.2,
                    width: availableSquare ? availableSquare.square.width / $container.width() : 0.3,
                    square_index: availableSquare ? availableSquare.index : -1,
                    tmpId: tools.tmpId(),
                    mapType: type,
                    isDrill: false,
                    dimension: [],
                    measure2: [],
                    measure: [],
                    sortField: '',
                    sortType: '',
                    ctitle: '',
                    moduleId: '',

                };

                if (config) {
                    angular.extend(mapConfig, config);
                }

                scope.maps.push(mapConfig);

                // 标注某一个可用的框已经被使用了
                if (availableSquare) {
                    availableSquare.square.used = true;
                }
            });

            // 新增表
            events.ADD_SHEET_EV_OFF = $rootScope.$on('ADD_SHEET_EV', function (e, type, config) {
                var $container = $(element).find('.charts-container');
                var availableSquare = getAvailableSquare();
                var sheetConfig = {
                    left: availableSquare ? availableSquare.square.left / $container.width() : ($ele.scrollLeft() + 100) / $container.width(),
                    top: availableSquare ? availableSquare.square.top / $container.width() : ($ele.scrollTop() + 100) / $container.width(),
                    height: availableSquare ? availableSquare.square.height / $container.width() : 0.2,
                    width: availableSquare ? availableSquare.square.width / $container.width() : 0.3,
                    square_index: availableSquare ? availableSquare.index : -1,
                    dataFieldNames: [],
                    lineFieldNames: [],
                    listFieldNames: [],
                    tmpId: tools.tmpId(),
                    isDrill: false,
                    filters: {
                        sortField: '',
                        sortType: ''
                    },
                    tabType: type,
                    sortField: '',
                    sortType: '',
                    ctitle: '',
                    moduleId: '',
                    intervalPeriodUnit : {val:'month',name:'月'},
                    dateDimensionFieldName : [],
                    retentionMarkFieldName : [],
                };

                if (config) {
                    angular.extend(sheetConfig, config);
                }
                if (availableSquare) {
                    availableSquare.square.used = true;
                }

                scope.sheets.push(sheetConfig);
            });

            // 新增组件
            events.ADD_CONDITION_EV_OFF = $rootScope.$on('ADD_CONDITION_EV', function (e, type, column) {
                var $container = $(element).find('.charts-container');
                scope.conditions[type].push({
                    left: ($ele.scrollLeft() + 100) / $container.width(),
                    top: ($ele.scrollTop() + 100) / $container.width(),
                    tmpId: tools.tmpId(),
                    conditionId: '',
                    condType: type,
                    height: 0,
                    width: 0,
                    column: column || null
                });
            });

            // 新增文本
            events.ADD_TEXT_EV_OFF = $rootScope.$on('ADD_TEXT_EV', function (e, type) {
                var $container = $(element).find('.charts-container');
                scope.objects[type].push({
                    //left: ($ele.scrollLeft() + 50) / $ele.width(),
                    //top: ($ele.scrollTop() + 50) / $ele.width(),
                    left: ($ele.scrollLeft() + 100) / $container.width(),
                    top: ($ele.scrollTop() + 100) / $container.width(),
                    tmpId: tools.tmpId(),
                    textId: 0,
                    objType: type,
                    height: 0.15,
                    width: 0.15,
                    content: '',
                    style: {
                        fontSize: '14px'
                    }
                });
            });

            // 获取page json 事件
            events.GET_PAGE_JSON_EV_OFF = $rootScope.$on('GET_PAGE_JSON_EV', function (e, cb) {
                $rootScope.$broadcast('SAVE_EV');

                var charts_saved = [];
                var sheets_saved = [];
                var objects_saved = [];
                var conditions_saved = {
                    date: [],
                    note: [],
                    radio: [],
                    select: [],
                    between: [],
                    checkbox: [],
                    textarea: [],
                    images: []
                };

                for (var i = 0; i < scope.charts.length; i++) {
                    if (scope.charts[i].moduleId) {
                        charts_saved.push(scope.charts[i]);
                    }
                }

                for (var i = 0; i < scope.sheets.length; i++) {
                    if (scope.sheets[i].moduleId) {
                        sheets_saved.push(scope.sheets[i]);
                    }
                }

                for (var i in scope.conditions) {
                    for (var j = 0; j < scope.conditions[i].length; j++) {
                        if (scope.conditions[i][j].conditionId) {
                            conditions_saved[i].push(scope.conditions[i][j]);
                        }
                    }
                }

                var json_ = JSON.stringify({
                    core: {
                        charts: charts_saved,
                        sheets: sheets_saved,
                        squares: scope.squares,
                        objects: scope.objects,
                        conditions: conditions_saved
                    }

                });
                json_ = json_.replace(/:null/gi, ':""');
                cb && cb(json_);
            });

            scope.$on('$destroy', function () {
                for (var i in events) {
                    if (i.indexOf('_OFF') != -1) {
                        events[i]();
                    }
                }
            });

            scope.mobileEnv = tools.mobileEnv;


            $rootScope.$broadcast('CONTEXTMENU_OFF_EV');
        },
        templateUrl: "/trend-new-BI/app/components/common/chartManager/chartManagerView.html"
    }
}]);